const Router = require("@koa/router");
const router = new Router();
const {
  ArticleKeyword,
  Atrcliepblish,
  AtrcliepblishVideo,
  CompanionDatails,
  Comment,
  Commentget,
  Concern,
  Classifytravels,
  Resreturn,
} = require("@/config/valiData");
const {
  modelArticle,
  modelUser,
  modelLike,
  modelCollection,
  modelComment,
  modelConcern,
} = require("@/models/collection");
const { Auth } = require("@/token/auth");
//百度ai关键词提取
const aiKeyword = require("@/aikeyword/index");
const moment = require("moment");
moment.locale("zh-cn");

//计算图片匡高
const imageInfo = require("@/config/image.info");

const { Authuid } = require("@/token/auth_uid");
const mongoose = require("mongoose");

const { looKup, looKupConcer } = require("../../config/lookup");

//更新moment时间格式
moment.updateLocale("zh-cn", {
  relativeTime: {
    future: "in %s内",
    past: "%s 前",
    s: "刚刚",
    ss: "%d 秒",
    m: "1 分钟",
    mm: "%d 分钟",
    h: "1 小时",
    hh: "%d 小时",
    d: "1 天",
    dd: "%d 天",
    w: "1 周",
    ww: "%d 周",
    M: "1 月",
    MM: "%d 月",
    y: "1 年",
    yy: "%d 年",
  },
});
//分析游记关键词
router.post("/article-keyword", async (ctx) => {
  const { text } = ctx.request.body;
  ArticleKeyword(text);
  if (text.trim() === "") {
    ctx.send("SUCCESS", 200, []);
    return false;
  }
  const res = await aiKeyword(text);
  const aitext = res.map((item) => item.word);
  const newarr = ["摄影", "自驾", "自由行", "徒步", ...aitext];
  console.log(res, ...newarr);
  ctx.send("SUCCESS", 200, newarr);
});

//发布游记:图片类型
router.post("/article-publish", new Auth().m, async (ctx) => {
  const { title, content, image, city, address, province, tag } =
    ctx.request.body;
  Atrcliepblish(title, content, image, city, address, province, tag);
  //获取封面图宽高
  const imageUrl = await imageInfo(image[0]);
  const userUid = await modelUser
    .findOne({ uid: ctx.auth.uid }, { _id: true })
    .lean();
  const user_id = userUid._id.toString();

  const saveRes = await modelArticle.create({
    author_uid: ctx.auth.uid,
    author_id: user_id,
    title,
    content,
    cover_image: {
      url: image[0],
      width: imageUrl.width,
      height: imageUrl.height,
    },
    image,
    city,
    address,
    province,
    tag,
  });

  console.log(saveRes);
  //去重
  await modelArticle.findOneAndUpdate(
    { _id: saveRes._id },
    { $addToSet: { tag: { $each: tag } } }
  );
  ctx.send("SUCCESS", ctx, 200);
  //更新用户标签
  await modelUser.findOneAndUpdate(
    { _id: user_id },
    { $addToSet: { my_tags: { $each: tag } } }
  );
});

//发布游记：视频类型
router.post("/article-publish-Video", new Auth().m, async (ctx) => {
  const {
    title,
    content,
    city,
    address,
    province,
    tag,
    videoPoster,
    videoUrl,
    videoWidth,
    videoHeight,
  } = ctx.request.body;
  AtrcliepblishVideo(
    title,
    content,
    city,
    address,
    province,
    tag,
    videoPoster,
    videoUrl,
    videoWidth,
    videoHeight
  );
  const imageUrl = await imageInfo(videoPoster);
  const userUid = await modelUser
    .findOne({ uid: ctx.auth.uid }, { _id: true })
    .lean();
  const user_id = userUid._id.toString();

  const saveRes = await modelArticle.create({
    author_uid: ctx.auth.uid,
    author_id: user_id,
    title,
    content,
    cover_image: {
      url: videoPoster,
      width: imageUrl.width,
      height: imageUrl.height,
    },
    city,
    address,
    province,
    tag,
    videoUrl: {
      url: videoUrl,
      width: videoWidth,
      height: videoHeight,
    },
    fileType: "video",
  });
  console.log(saveRes);
  //去重
  await modelArticle.findOneAndUpdate(
    { _id: saveRes._id },
    { $addToSet: { tag: { $each: tag } } }
  );
  ctx.send("SUCCESS", ctx, 200);
  //更新用户标签
  await modelUser.findOneAndUpdate(
    { _id: user_id },
    { $addToSet: { my_tags: { $each: tag } } }
  );
});

//用户给游记点赞
router.get("/user-like", new Auth().m, async (ctx) => {
  const { article_id } = ctx.query;
  CompanionDatails(article_id);
  const exist = await modelLike.findOne({ article_id, user_uid: ctx.auth.uid });
  if (exist === null) {
    const authorUid = await modelArticle
      .findOne({ _id: article_id }, { author_uid: true })
      .lean();
    const userUid = await modelUser
      .findOne({ uid: ctx.auth.uid }, { _id: true })
      .lean();
    await modelLike.create({
      user_uid: ctx.auth.uid,
      author_uid: authorUid.author_uid,
      user_id: userUid._id,
      article_id,
    });
    ctx.send("SUCCESS", 200, "点赞成功");
  } else {
    ctx.send("SUCCESS", 200, "已赞");
  }
});

//取消用户点赞
router.get("/cancel-like", new Auth().m, async (ctx) => {
  const { article_id } = ctx.query;
  CompanionDatails(article_id);
  const res = await modelLike.deleteMany({
    user_uid: ctx.auth.uid,
    article_id,
  });
  if (res.deletedCount > 0) {
    ctx.send();
  } else {
    ctx.send("取消点赞失败", 422);
  }
});

//用户收藏游记
router.get("/collect-travel", new Auth().m, async (ctx) => {
  const { article_id } = ctx.query;
  CompanionDatails(article_id);
  const exist = await modelCollection.findOne({
    article_id,
    user_uid: ctx.auth.uid,
  });
  if (exist === null) {
    const authorUid = await modelArticle
      .findOne({ _id: article_id }, { author_uid: true })
      .lean();
    const userUid = await modelUser
      .findOne({ uid: ctx.auth.uid }, { _id: true })
      .lean();
    await modelCollection.create({
      user_uid: ctx.auth.uid,
      author_uid: authorUid.author_uid,
      user_id: userUid._id,
      article_id,
    });
    ctx.send("SUCCESS", 200, "收藏成功");
  } else {
    ctx.send("SUCCESS", 200, "已收藏");
  }
});

//取消用户收藏
router.get("/cancel-collect", new Auth().m, async (ctx) => {
  const { article_id } = ctx.query;
  CompanionDatails(article_id);
  const res = await modelCollection.deleteMany({
    user_uid: ctx.auth.uid,
    article_id,
  });
  if (res.deletedCount > 0) {
    ctx.send();
  } else {
    ctx.send("取消收藏失败", 422);
  }
});

//用户评论游记
router.post("/comment-travel", new Auth().m, async (ctx) => {
  const { article_id, comment_content } = ctx.request.body;
  Comment(article_id, comment_content);
  const authorUid = await modelArticle
    .findOne({ _id: article_id }, { author_uid: true })
    .lean();
  const userUid = await modelUser.findOne({ uid: ctx.auth.uid }, {}).lean();
  const res = await modelComment.create({
    user_uid: ctx.auth.uid,
    author_uid: authorUid.author_uid,
    user_id: userUid._id,
    article_id,
    content: comment_content,
  });
  console.log(res);
  const resObj = {
    _id: res._id,
    article_id,
    content: comment_content,
    time: res.time,
    user_uid: ctx.auth.uid,
    comment_user: [
      {
        avatarUrl: userUid.avatarUrl,
        nickname: userUid.nickname,
      },
    ],
    isComment_user: true,
  };
  ctx.send("SUCCESS", 200, resObj);
});

//删除评论
router.get("/comments-delete", new Auth().m, async (ctx) => {
  const { comment_id } = ctx.query;
  CompanionDatails(comment_id);
  //判断是否删除为用户自己的+评论
  const res = await modelComment.find({
    _id: comment_id,
    user_uid: ctx.auth.uid,
  });
  if (res.length <= 0) {
    ctx.send("SUCCESS", 422, { messageL: "评论不存在或者不能删除别人的评论" });
    return false;
  }
  await modelComment.deleteMany({ _id: comment_id });
  ctx.send();
});

//获取评论数据:需要考虑用户在登录的情况下，是可以删除评论的
router.get("/comments-data", new Authuid().m, async (ctx) => {
  const { article_id, page } = ctx.query;
  Commentget(article_id, page);
  const myUid = ctx.auth.uid ? ctx.auth.uid : "m";
  const res = await modelComment.aggregate([
    { $match: { article_id: new mongoose.Types.ObjectId(article_id) } },
    { $sort: { timestamp: -1 } },
    { $skip: (page - 1) * 7 },
    { $limit: 10 },
    {
      $lookup: {
        //链接用户表
        from: modelUser.collection.name,
        localField: "user_uid",
        foreignField: "uid",
        as: "comment_user",
      },
    },
    {
      $project: {
        _id: 1,
        article_id: 1,
        content: 1,
        time: 1,
        user_uid: 1,
        "comment_user.nickname": 1,
        "comment_user.avatarUrl": 1,
        isComment_user: {
          $cond: {
            //类似三元表达
            if: { $eq: ["$user_uid", myUid.uid] },
            then: true,
            else: false,
          },
        },
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

//关注接口
router.get("/follow-author", new Auth().m, async (ctx) => {
  const { im_concerned_uid } = ctx.query;
  Concern(im_concerned_uid);

  // 检查是否是自己
  if (im_concerned_uid === ctx.auth.uid) {
    ctx.send("SUCCESS", 422, "不能关注自己");
    return false;
  }

  //是否已经关注过
  const exist = await modelConcern.findOne({
    // 改用 findOne
    user_uid: ctx.auth.uid,
    im_concerned_uid,
  });

  if (!exist) {
    // 改为判断是否存在
    await modelConcern.create({
      user_uid: ctx.auth.uid,
      im_concerned_uid,
    });
    ctx.send("SUCCESS", 200, "关注成功");
  } else {
    ctx.send("SUCCESS", 200, "已经关注过了");
  }
});

//取消关注
router.get("/unfollow-author", new Auth().m, async (ctx) => {
  const { im_concerned_uid } = ctx.query;
  Concern(im_concerned_uid);

  // 使用 deleteOne 替代 deleteMany，因为一个用户只能关注另一个用户一次
  const result = await modelConcern.deleteOne({
    user_uid: ctx.auth.uid,
    im_concerned_uid,
  });

  if (result.deletedCount > 0) {
    ctx.send("SUCCESS", 200, "取消关注成功");
  } else {
    ctx.send("SUCCESS", 422, "取消关注失败，可能未关注该用户");
  }
});

// 进入游记详情页：多表查询
router.get("/article-data", new Authuid().m, async (ctx) => {
  const { article_id } = ctx.query;
  Concern(article_id);
  const myUid = ctx.auth.uid ? ctx.auth.uid : "m";
  const test = await modelArticle.find({ _id: article_id });
  console.log(test);

  const res = await modelArticle.aggregate([
    { $match: { _id: new mongoose.Types.ObjectId(article_id) } },
    looKup().model_user, //连接用户表
    looKup().model_like,
    looKup().model_collection,
    looKup().model_comment,
    {
      $lookup: {
        from: modelConcern.collection.name,
        localField: "author_uid",
        foreignField: "im_concerned_uid",
        as: "concernedUsers",
      },
    },
    {
      $project: {
        _id: 1,
        author_id: 1,
        title: 1,
        content: 1,
        image: 1,
        videoUrl: 1,
        city: 1,
        address: 1,
        time: 1,
        likes: { $size: "$likes" }, //计算点赞数量
        comments: { $size: "$comments" }, //计算评论数量
        collections: { $size: "$collections" }, //计算收藏数量
        "author_data._id": 1,
        "author_data.nickname": 1,
        "author_data.uid": 1,
        "author_data.avatarUrl": 1,
        myuid: myUid.uid,
        isLike: {
          $in: [myUid.uid, "$likes.user_uid"], //判断是否点赞
        },
        isCollections: {
          $in: [myUid.uid, "$collections.user_uid"], //判断是否收藏
        },
        isConcerned: {
          $in: [myUid.uid, "$concernedUsers.user_uid"], //判断是否关注
        },
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 进入游记详情页：底部相关游记
router.get("/rec-the-same", async (ctx) => {
  const { article_id, page } = ctx.query;
  Commentget(article_id, page);
  const articleCity = await modelArticle.find({ _id: article_id }).lean();
  console.log(articleCity);
  const query = { $regex: articleCity[0].city, $options: "i" };
  const articleId = new mongoose.Types.ObjectId(article_id); //转换类型
  const userTravels = await modelArticle.aggregate([
    {
      $match: {
        $and: [
          {
            $or: [{ city: query }, { address: query }, { province: query }],
          },
          {
            _id: { $nin: [articleId] }, //排除当前游记
          },
        ],
      },
    },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().model_collection,
    looKup().projectcard,
  ]);
  ctx.send("SUCCESS", 200, userTravels);
});

//进入游记详细页：短视频类型
router.get("/rec-the-video", new Authuid().m, async (ctx) => {
  const { article_id, page } = ctx.query;
  Commentget(article_id, page);
  const articleId = new mongoose.Types.ObjectId(article_id); //转换类型
  const myUid = ctx.auth.uid ? ctx.auth.uid : "m";
  const userTravels = await modelArticle.aggregate([
    {
      $match: {
        fileType: "video",
        id: { $nin: [articleId] },
      },
    },
    { $skip: (page - 1) * 4 },
    { $limit: 6 },
    looKup().model_user, //连接用户表
    looKup().model_like,
    looKup().model_collection,
    looKup().model_comment,
    {
      $lookup: {
        from: modelConcern.collection.name,
        localField: "author_uid",
        foreignField: "im_concerned_uid",
        as: "concernedUsers",
      },
    },
    {
      $project: {
        _id: 1,
        author_id: 1,
        title: 1,
        content: 1,
        videoUrl: 1,
        address: 1,
        time: 1,
        likes: { $size: "$likes" }, //计算点赞数量
        comments: { $size: "$comments" }, //计算评论数量
        collection: { $size: "$collections" }, //计算收藏数量
        "author_data._id": 1,
        "author_data.nickname": 1,
        "author_data.uid": 1,
        "author_data.avatarUrl": 1,

        isLike: {
          $in: [myUid.uid, "$likes.user_uid"], //判断是否点赞
        },
        isCollections: {
          $in: [myUid.uid, "$collections.user_uid"], //判断是否收藏
        },
        isConcerned: {
          $in: [myUid.uid, "$concernedUsers.user_uid"], //判断是否关注
        },
      },
    },
  ]);
  ctx.send("SUCCESS", 200, userTravels);
});

//获取首页瀑布流游记
router.get("/user-travels", async (ctx) => {
  const { keywords, page } = ctx.query;
  Classifytravels(keywords, page);
  let match = {};
  if (keywords === "001") {
    match = {};
  } else if (keywords === "002") {
    //取当前月份月初和月末的时间戳
    const startOfMonth = moment().clone().startOf("month").unix();
    const endOfMonth = moment().clone().endOf("month").unix();
    match = {
      time_stamp: {
        $gte: startOfMonth, //大于等于当前月份月初
        $lte: endOfMonth, //小于等于当前月份月末
      },
    };
  } else {
    const arr = [
      { name: "露营", key: "003" },
      { name: "古镇漫游", key: "004" },
      { name: "徒步骑行", key: "005" },
      { name: "躺酒店", key: "006" },
      { name: "宝藏小城", key: "007" },
      { name: "亲子游", key: "008" },
      { name: "博物馆", key: "009" },
      { name: "摄影", key: "010" },
      { name: "海景", key: "011" },
    ];
    const result = arr.filter((item) => item.key === keywords);
    match = { tag: { $in: [result[0].name] } };
  }
  const res = await modelArticle.aggregate([
    { $match: match },
    { $sort: { time_stamp: -1 } },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().projectcard,
  ]);
  ctx.send("SUCCESS", 200, res);
});

//获取用户的点赞，关注，粉丝数量
router.get("/my-related", new Auth().m, async (ctx) => {
  //我收到的点赞数量
  const likeCount = await modelLike.countDocuments({
    author_uid: ctx.auth.uid,
  });
  //我关注的数量
  const concernCount = await modelConcern.countDocuments({
    user_uid: ctx.auth.uid,
  });
  //我的粉丝数量
  const fansCount = await modelConcern.countDocuments({
    im_concerned_uid: ctx.auth.uid,
  });
  ctx.send("SUCCESS", 200, { likeCount, concernCount, fansCount });
});

//查询用户发表的游记
router.get("/myTravEls", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelArticle
    .find({
      author_uid: ctx.auth.uid,
    })
    .sort({ time_stamp: -1 })
    .skip((page - 1) * 6)
    .limit(6)
    .select("address cover_image fileType");
  ctx.send("SUCCESS", 200, res);
});

//查询用户收藏的游记
router.get("/myCollEction", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const articleIds = await modelCollection.find(
    { user_uid: ctx.auth.uid },
    { article_id: true }
  );

  const res = await modelArticle
    .find({ _id: { $in: articleIds.map((item) => item.article_id) } })
    .sort({ time_stamp: -1 })
    .skip((page - 1) * 6)
    .limit(6)
    .select("_id address cover_image fileType");

  ctx.send("SUCCESS", 200, res);
});
//查询用户点过赞的游记
router.get("/myLikeArticle", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const articleIds = await modelLike.find(
    { user_uid: ctx.auth.uid },
    { article_id: true }
  );
  const res = await modelArticle
    .find({ _id: { $in: articleIds.map((item) => item.article_id) } })
    .sort({ time_stamp: -1 })
    .skip((page - 1) * 6)
    .limit(6)
    .select("_id address cover_image fileType");
  ctx.send("SUCCESS", 200, res);
});

//获取用户关注的作者信和游记
router.get("/user-following-author", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  //获取用户关注的作者uid
  const imcUId = await modelConcern.find(
    { user_uid: ctx.auth.uid },
    { im_concerned_uid: true }
  );
  const imcUidMap = imcUId.map((item) => item.im_concerned_uid);
  //获取点赞表里的游记_id
  const likeArtId = await modelLike.find(
    { user_uid: ctx.auth.uid },
    { article_id: true }
  );
  const LikeArtIdMap = likeArtId.map((item) => item.article_id);
  //获取收藏表里面的游记_id
  const collctArtId = await modelCollection.find(
    { user_uid: ctx.auth.uid },
    { article_id: true }
  );
  const collctArtIdMap = collctArtId.map((item) => item.article_id);
  const res = await modelArticle.aggregate([
    { $match: { author_uid: { $in: imcUidMap } } },
    { $sort: { time_stamp: -1 } },
    {
      $group: {
        _id: "$author_uid",
        articles: { $push: "$$ROOT" }, //将符合条件的游记放入articles数组
      },
    },
    {
      $project: {
        _id: 0,
        author_uid: "$_id",
        articles: {
          $slice: ["$articles", 3],
        },
      },
    },
    {
      $unwind: "$articles", //将articles数组拆分成单个游记对象
    },
    looKup().model_user,
    looKupConcer("articles._id").model_like,
    looKupConcer("articles._id").model_comment,
    looKupConcer("articles._id").model_collection,
    {
      $project: {
        _id: "$articles._id",
        title: "$articles.title",
        content: "$articles.content",
        image: "$articles.image",
        address: "$articles.address",
        cover_image: "$articles.cover_image",
        videoUrl: "$articles.videoUrl",
        fileType: "$articles.fileType",
        time_stamp: "$articles.time_stamp",
        likes: { $size: "$likes" }, //点赞数量
        comments: { $size: "$comments" },
        collections: { $size: "$collections" },
        "author_data.avatarUrl": 1,
        "author_data.nickname": 1,
        isLiked: {
          $cond: {
            if: { $in: ["$articles._id", LikeArtIdMap] },
            then: true,
            else: false,
          },
        },
        isCollect: {
          $cond: {
            if: { $in: ["$articles._id", collctArtIdMap] },
            then: true,
            else: false,
          },
        },
      },
    },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
  ]);
  res.forEach((item) => {
    const diff = moment().diff(item.time_stamp * 1000, "seconds");
    item.time_stamp =
      diff < 60 ? "刚刚" : moment(item.time_stamp * 1000).fromNow();
  });
  ctx.send("SUCCESS", 200, res);
});

module.exports = router.routes();
